package jk.spider.util;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class CookieUtil {
	private static final Logger log = Logger.getLogger(CookieUtil.class);
	private static Selenium browser;
	private static CookieUtil g;
	private volatile boolean lock = false;
	private volatile int rCount = 0;

	public CookieUtil() {
		browser = new DefaultSelenium("localhost", 4444, "*iexplore",
				"http://www.googel.com");
		browser.start();
	}

	public synchronized static CookieUtil getBrowser() {
		if (g == null) {
			g = new CookieUtil();
		}
		return g;
	}

	public synchronized String requestCookie() {
		rCount ++;
		if(rCount % 5 == 0) 
			this.cleanCookie();
		
		String cookie = "";
		try {
			browser.open("http://www.dianping.com");
			browser.click("$h_m_b");
			browser.waitForPageToLoad("50000");
			cookie = browser.getCookie();
			if (!SpiderUtil.isStringNull(cookie)) {
				return cookie;
			} else {
				this.requestCookie();
			}
		} catch (Exception e) {
			CookieUtil g = getBrowser();
			g.requestCookie();
		}
		return cookie;
	}

	public Selenium getSelenium() {
		return browser;
	}

	public void Close() {
		browser.close();
	}

	public void cleanCookie() {
		synchronized (this) {
			if (lock) {
				try {
					this.wait();
					return;
				} catch (InterruptedException e) {
					log.warn("cleanCookie InterruptedException -> ", e);
				}
			}
		}
		lock = true;
		try {
			log.info("RunDll32.exe Clean Cookie");
			Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");
//			Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1");
//			try {
//				TimeUnit.SECONDS.sleep(30);
//			} catch (InterruptedException e) {
//			}
			
		} catch (IOException e) {
			log.warn("cleanCookie IOException -> ", e);
		}
		synchronized (this) {
			lock = false;
			this.notifyAll();
		}
	}

	public static void main(String[] args) {
		CookieUtil g = CookieUtil.getBrowser();
		System.out.println(g.requestCookie());

	}
}
